package net.mikoo.seals.api.controller;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.model.wechat.GetOpenIdRequest;
import net.mikoo.seals.api.model.wechat.GetOpenIdResponse;
import net.mikoo.seals.api.utility.ApiConstants;
import net.mikoo.seals.common.HttpUtil;

@Controller
public class WeChatController {

	private final static String GETOPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
	
	private static Logger logger = LoggerFactory.getLogger(WeChatController.class);
	
	@RequestMapping("/wechat/getOpenId")
	@ResponseBody
	public GetOpenIdResponse getOpenId(GetOpenIdRequest request){
		GetOpenIdResponse result = new GetOpenIdResponse();
		try {
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			if(StringUtils.isBlank(request.getCode())) {
				throw new IllegalArgumentException("request.getCode");
			}
			
			String res = HttpUtil.get(String.format(GETOPENID_URL, ApiConstants.WX_APP_ID, ApiConstants.WX_APP_SECRET, request.getCode()));
			JSONObject json = JSONObject.parseObject(res);
			if(json == null) {
				throw new RuntimeException("get openId request fail");
			}
			result.setResult(ResultType.SUCCESS.getValue());
			result.setOpenId(json.getString("openid"));
			result.setUnionid(json.getString("unionid"));
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
}
